package cn.com.dcsgo.controller;

import cn.com.dcsgo.model.acl.Permission;
import cn.com.dcsgo.result.Result;
import cn.com.dcsgo.service.PermissionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.List;

/*
接口请求路径、请求方式、请求参数参考前端文件：
uu-preferred-front-end/uuyx-admin/src/api/acl/permission.js
 */

/**
 * PermissionController
 *
 * @author Dcsgo
 * @since 2025/3/24 21:07
 */
@Slf4j
@RestController
@Api(tags = "权限(菜单)接口")
@RequiredArgsConstructor
@RequestMapping("/admin/acl/permission")
public class PermissionController {
    private final PermissionService permissionService;

    /**
     * 获取权限列表-层级结构
     *
     * @return Result->List->Permission
     */
    @GetMapping
    @ApiOperation("获取权限列表-层级结构")
    public Result<List<Permission>> getPermissionList() {
        return Result.ok(permissionService.allPermissionOfHierarchicalStruct());
    }

    /**
     * 添加权限
     *
     * @param permission permission
     * @return Result->null
     */
    @PostMapping("save")
    @ApiOperation("添加权限")
    public Result<Serializable> addPermission(@RequestBody Permission permission) {
        if (permissionService.save(permission)) {
            return Result.ok(null);
        }
        log.error("添加权限: {},失败！", permission);
        return Result.fail(null);
    }

    /**
     * 修改权限
     *
     * @param permission permission
     * @return Result->null
     */
    @ApiOperation("修改权限")
    @PutMapping("update")
    public Result<Serializable> updatePermission(@RequestBody Permission permission) {
        if (permissionService.updateById(permission)) {
            return Result.ok(null);
        }
        log.error("修改权限: {},失败！", permission);
        return Result.fail(null);
    }

    /**
     * 删除权限(递归)
     *
     * @param id id
     * @return Result->null
     */
    @ApiOperation("删除权限(递归)")
    @DeleteMapping("remove/{id}")
    public Result<Serializable> removePermission(@PathVariable Long id) {
        permissionService.removeContainChild(id);
        return Result.ok(null);
    }

    /**
     * 通过角色id获取权限列表
     *
     * @param roleId roleId
     * @return Result->List->Permission
     */
    @ApiOperation("通过角色id获取权限列表")
    @GetMapping("toAssign/{roleId}")
    public Result<List<Permission>> toAssign(@PathVariable Long roleId) {
        return Result.ok(permissionService.getPermissionListByRoleId(roleId));
    }

    /**
     * @param roleId        roleId
     * @param permissionIds permissionIds
     * @return Result->null
     */
    @PostMapping("doAssign")
    @ApiOperation("给角色分配权限")
    public Result<Serializable> doAssign(@RequestParam Long roleId, @RequestParam("permissionId") Long[] permissionIds) {
        permissionService.assignPermission(roleId, permissionIds);
        return Result.ok(null);
    }
}
